local mt = {}
ac.game = mt

mt.name = '游戏数据'

--星期几
mt.week = 0

--游戏开始时间
function mt:game_start()
    return MsGetRoomStartTs()
end

--房间游戏模式
function mt:game_mode()
    return MsGetRoomModeId()
end

--脚本加载时间
function mt:game_Loaded()
    return MsGetRoomLoadedTs()
end

--游戏运行时间
function mt:get_time()
    return MsGetRoomGameTime()
end

--当前时间戳
function mt:get_timestamp()
    return self:game_start() + self:get_time()
    --return 1734837075
end

--玩家数量
function mt:get_player_count()
    return MsGetRoomPlayerCount()
end


--- 派发全局事件(有返回值)
--- @param name string
--- @param ... any
--- @return function
function mt:dispatch(name, ...)
	return ac.dispatch(self, name, ...)
end

--- 派发全局事件
--- @param name string
--- @param ... any
--- @return function
function mt:notify(name, ...)
	return ac.notify(self, name, ...)
end

--- 注册全局事件
--- @param name string
--- @return function
function mt:event(name)
	return ac.register(self, name)
end


--房间加载完毕后
RegisterEvent('_roomloaded', function(id, ename, evalue, player_index)
    ac.game:notify('游戏-房间加载完毕后',id, ename, evalue, player_index)
end)

ac.game:event '游戏-房间加载完毕后'(function(trg,id, ename, evalue, player_index)
    trg:remove()
    local t = os.date('*t',ac.game:get_timestamp())
    ac.game.week = (t['wday'] - 1)%7
    local room_info = json.decode(evalue)
    local players = room_info['players']
    math.randomseed(os.time())
    ac.game:notify('游戏-房间加载完毕')
    for _,id in ipairs(players) do
        local id = math.floor(id)
        local player = ac.player[id]
        ac.eventPlayer = player
        player:loaded()
    end
    ac.game:notify('游戏-玩家初始化完毕')
    math.randomseed(os.time())
end)


--房间结束后
RegisterEvent('_roomover', function(id, ename, evalue, player_index)
    --无数据是本地
    for a=0,12 do
        local player = ac.player[a]
        if player:is_player() then
            player:exit_game()
        end
    end
    -- 对局结束
    MsEnd(-1, "room_over")
end)


--玩家退出游戏
RegisterEvent('_playerexit', function(id, ename, evalue, player_index)
    local player = ac.player[player_index]
    LogInfo("玩家退出%s", player)
    player:exit_game()
end)


-- 玩家离开游戏，可能断线重连回来
RegisterEvent('_playerleave', function(id, ename, evalue, player_index)
    local player = ac.player[player_index]
    ac.game:notify('玩家-离开游戏',player,evalue)
end)

--玩家重新加入游戏
RegisterEvent('_playerjoin', function(id, ename, evalue, player_index)
    local player = ac.player[player_index]
    ac.game:notify('玩家-重新加入',player,evalue)
end)